package top.codedance.iotp.tools.terminal.ui;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.tools.terminal.TerminalApplication;

import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author xuedianfu
 */
public class AddResetClient extends javax.swing.JDialog {

    private ClientPluginTester cpt;
    private int rowIndex = -1;

    /**
     * Creates new form AddResetClient
     */
    public AddResetClient(ClientPluginTester cpt, JSONObject initData) {
        super(cpt, true);
        this.cpt = cpt;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(this.cpt.getShellFrame());
        setMinimumSize(new Dimension(400, 200));
        setTitle("代码飞舞采控系统-添加重启客户端");

        initEditData(initData);
    }

    private void initEditData(JSONObject initData){
        if(initData != null){
            JSONObject client = initData.getJSONObject("client");
            jcb_isExceptionExit.setSelected(client.getBoolean("isExceptionExit"));
            jtf_minute.setText(client.getString("amount"));
            rowIndex = initData.getIntValue("rowIndex");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jcb_isExceptionExit = new javax.swing.JCheckBox();
        jLabel3 = new javax.swing.JLabel();
        jtf_minute = new javax.swing.JTextField();
        jb_add = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("重启客户端");

        jLabel2.setText("是否异常退出：");

        jcb_isExceptionExit.setText("是");

        jLabel3.setText("几秒后退出：");

        jtf_minute.setText("10");
        jtf_minute.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtf_minuteKeyTyped(evt);
            }
        });

        jb_add.setText("保存为命令");
        jb_add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_addActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtf_minute)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jcb_isExceptionExit)
                                .addGap(0, 182, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(130, 130, 130))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jb_add)
                                .addGap(115, 115, 115))))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jcb_isExceptionExit))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtf_minute, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jb_add)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private String getTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date());
    }

    private void jb_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_addActionPerformed
        JSONObject commandParams = new JSONObject();
        commandParams.put("plugin", Command.SHUTDOWN);
        JSONObject clientJo = new JSONObject();
        clientJo.put("isExceptionExit", jcb_isExceptionExit.isSelected());
        clientJo.put("amount", Integer.valueOf(jtf_minute.getText()));
        commandParams.put("client", clientJo);
        if(rowIndex < 0) {
            String defaultName = "RebootClient-" + getTime();
            String name = (String) JOptionPane.showInputDialog(this, "如需重新起名，请输入新的名称。", "保存命令", JOptionPane.QUESTION_MESSAGE, null, null, defaultName);
            if (name == null || name.isEmpty()) {
                name = defaultName;
            }
            cpt.addPluginParam(commandParams, name);
        }else{
            cpt.addPluginParam(commandParams, rowIndex);
        }
        setVisible(false);
    }//GEN-LAST:event_jb_addActionPerformed

    private void jtf_minuteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtf_minuteKeyTyped
        JTextField jtf = (JTextField)evt.getSource();
        if (!TerminalApplication.numbers.contains(evt.getKeyChar())) {
            evt.consume();
        }
        try{
            Integer.parseInt(jtf.getText());
            if(jtf.getText().startsWith("0")){
                jtf.setText(jtf.getText().replaceAll("^0+", ""));
            }
        }catch (Exception e){
            jtf.setText("0");
        }
    }//GEN-LAST:event_jtf_minuteKeyTyped

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton jb_add;
    private javax.swing.JCheckBox jcb_isExceptionExit;
    private javax.swing.JTextField jtf_minute;
    // End of variables declaration//GEN-END:variables
}
